package com.lcp.se.service;

import com.alibaba.fastjson.JSONObject;
import com.lcp.se.config.ServerInfoConfig;
import com.lcp.se.server.ImServer;
import com.lcp.se.util.MessageProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 监听队列并处理队列中的消息
 *
 * @author lcp
 * @date 2020/7/26 11:22
 */
@Service
public class AmqpMessageService {
    private final Logger log = LoggerFactory.getLogger(ServerInfoConfig.class);

    @Value("${mini-program.msg-exchange-name}")
    private String exchangeName;

    @Resource
    private AmqpAdmin amqpAdmin;

    @Resource
    private ImServer imServer;

    /**
     * 初始化操作，向 rabbitmq 注册一个队列，并使用 im 和 ServerInfoConfig.serverInfo 两个 routingKey
     * 将注册的队列绑定到用于 msg 转发的交换机上
     */
    @PostConstruct
    public void init() {
        log.info("初始化队列：" + ServerInfoConfig.serverInfo + " 的绑定关系");
        amqpAdmin.declareExchange(new DirectExchange(exchangeName, true, false));
        amqpAdmin.declareBinding(new Binding(ServerInfoConfig.serverInfo, Binding.DestinationType.QUEUE, "se.msg" +
                ".direct", ServerInfoConfig.serverInfo, null));
        amqpAdmin.declareBinding(new Binding(ServerInfoConfig.serverInfo, Binding.DestinationType.QUEUE, "se.msg" +
                ".direct", "im", null));
        log.info("队列初始化完毕");
    }

    @Bean
    public Queue queue() {
        log.info("初始化队列：" + ServerInfoConfig.serverInfo);
        return new Queue(ServerInfoConfig.serverInfo, false, true, true);
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(exchangeName, true, false);
    }

    // spel 表达式
    @RabbitListener(queues = "#{queue.name}")
    public void receiveMessage(JSONObject msg) {
        String msgProp = msg.getString(MessageProperty.KEY_MESSAGE_PROPERTY);
        log.info(msg.toJSONString());
        if (MessageProperty.MSG_CHAT.equals(msgProp)) {
            String toUserOpenId = msg.getJSONObject(MessageProperty.KEY_DATA).getString("toUserOpenId");
            log.info("接收到一条发送给用户：" + toUserOpenId + " 的聊天消息");
            imServer.sendToOne(msg.toJSONString(), toUserOpenId);
            return;
        }
        if (MessageProperty.MSG_APPOINTMENT_ACCEPTED.equals(msgProp)) {
            String toUserOpenId = msg.getString(MessageProperty.KEY_DATA);
            log.info("接收到一条发送给用户：" + toUserOpenId + " 的预约已被接受");
            imServer.sendToOne(msg.toJSONString(), toUserOpenId);
        }
    }
}
